<?php

/**
 * category actions.
 *
 * @package    emc
 * @subpackage category
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class categoryActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  public function executeList(sfWebRequest $request)
  {
    $this->notify = $request->getParameter('notify');
    
    $con = Doctrine_Manager::getInstance()->connection();
    $parent_id = $request->getParameter('parent_id', null);
    $sql = "select c.id, c.parent_id, c.name, p.name as parent_name 
                FROM category c 
                LEFT JOIN category p ON p.id = c.parent_id 
                WHERE c.is_active = true AND c.id <> 1";
    if ($parent_id)
      $sql .= " AND c.parent_id = ".$parent_id;
    $st = $con->execute($sql);
    $this->categories = $st->fetchAll();
    $this->category_form = new AdminCategoryForm();
      
  	return sfView::SUCCESS;
  }
  
  public function executeEdit(sfWebRequest $request)
  {
    $data = $request->getParameter('category', null);
    if ($data) {
        if (isset($data['id']) && $data['id']) {
          $category = Doctrine_Core::getTable('Category')->find($data['id']);
          $notify = "update";
        } else {
          $category = new Category();
          $notify = "create";
        }
        $category->name = $data['name'];
        $category->parent_id = $data['parent_id'];
        $category->description = $data['description'];
        $category->href = $data['href'];
        $category->image = $data['image'];
        $category->is_active = isset($data['is_active']) ? true : false;
        $category->save();
        $this->redirect('@category_list?notify='.$notify.'_category_success');
      } else {
        $this->category_id = $request->getParameter('category_id', null);
        if ($this->category_id) { // it's an edit action
          $category = Doctrine_Core::getTable('Category')->find($this->category_id);
          $this->category_form = new AdminCategoryForm($category);
        }
      }
    return sfView::SUCCESS;
  }
  public function executeDelete(sfWebRequest $request)
  {
    $category_id = $request->getParameter('category_id', null);
    $category = Doctrine_Core::getTable('Category')->find($category_id);
    if ($category) {
      $category->deactivate();  
      $this->getRequest()->setParameter('notify', "category_deactive_success");
    } else {
        $this->getRequest()->setParameter('notify', "category_deactive_failed");
    }
    
    $this->forward('category', 'list');
  }
  
}
